package net.controllers;

import java.net.BindException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.form.processing.Image;
import net.form.processing.KMeans;
import net.form.processing.KMeansWithGrid;
import net.model.Background;
import net.model.RectangleReference;
import net.service.BackgroundManager;
import net.service.RectangleReferenceManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/kmeans")
public class KmeansController {

	private RectangleReference rectangleReference = null;
	private Background background= null;

	@Autowired
	private BackgroundManager backgroundManagerImpl;
	
	@Autowired
	private RectangleReferenceManager rectangleReferenceManagerImpl;

	@RequestMapping(method = RequestMethod.GET)
	public String getData(Model model, HttpSession session) {
		if (session.getAttribute("k") != null) {
			session.setAttribute("k", session.getAttribute("k"));
			session.setAttribute("nameOutFile",
					session.getAttribute("nameOutFile"));
		} else {
			session.setAttribute("k", "");
			session.setAttribute("nameOutFile", "");
		}
		return "/classificationkmeans";
	}
	
	@RequestMapping(params = "classifyKmeans", method = RequestMethod.POST)
	public String restoreBackground(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors,
			HttpSession session) {
		long start = System.currentTimeMillis();
		rectangleReference = rectangleReferenceManagerImpl
				.getRectangleReference();
		//Se obtiene el valor de k, el nombre del archivo de salida y el modo
		int k = getValueK(request);
		String nameOutFile = getNameOutFile(request);
		String mode = getMode(request);
		session.setAttribute("k", k);
		session.setAttribute("nameOutFile", nameOutFile);
		session.setAttribute("mode", mode);
		if (session.getAttribute("fullImageDirectory") != null) {
			// Nombre de archivo de entrada
			String fullImageDirectory = (String) session.getAttribute("fullImageDirectory");
			// Nombre de archivo de salida
			String originalFilename = ((String) session
					.getAttribute("nameOutFile")).concat(".jpg");
			int endIndex = fullImageDirectory.lastIndexOf("/");
			String fullOutKMeans = ((fullImageDirectory.substring(0, endIndex))
					.concat("/")).concat(originalFilename);
			// Modo
			int modeInt = 1;
			if (mode.equals("-i")) {
				modeInt = KMeans.MODE_ITERATIVE;
			} else if (mode.equals("-c")) {
				modeInt = KMeans.MODE_CONTINUOUS;
			}
			// create new KMeans object
			KMeansWithGrid kmeans = new KMeansWithGrid();
			// call the function to actually start the clustering
			net.form.processing.Image dstImage = kmeans
					.calculateWhitRangeFondo(
							Image.loadImage(fullImageDirectory), k, modeInt,
							backgroundManagerImpl.getBackground().getHSVRangeBackground());
			// save the resulting image
			Image.saveImage(fullOutKMeans, dstImage);
			
			session.setAttribute("uploadFile", "imagen\\" + originalFilename);
			
		}
		long end = System.currentTimeMillis();
		System.out.println("KMenas of object " + (end - start) + " ms.");
		return "/classificationkmeans";
	}

	private int getValueK(HttpServletRequest request) {
		int k = 0;
		if (request.getParameter("k") != "") {
			k = Integer.valueOf(request.getParameter("k"));
			if (!(k >= 0)) {
				k = 0;
			}
		}
		return k;
	}

	private String getNameOutFile(HttpServletRequest request) {
		String nameOutFile = "";
		if (request.getParameter("nameOutFile") != "") {
			nameOutFile = request.getParameter("nameOutFile");
			if (nameOutFile == null) {
				nameOutFile = "resultKMeans";
			}
		}
		return nameOutFile;
	}

	private String getMode(HttpServletRequest request) {
		String mode = null;
		if (request.getParameter("mode") != "") {
			mode = request.getParameter("mode");
			if (mode == null) {
				mode = "iterative";
			}
		}
		return mode;
	}
}
